package panels;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;

import javax.swing.JButton;
import javax.swing.JPanel;


public class JIntegerBox extends JFieldBox {

	/**
	 *  JNumberBox - For dealing with real numbers
	 */
	private static final long serialVersionUID = 1L;
	
	private JPanel	bPanel = null;
	private JButton	upButton = null;
	private JButton downButton = null;
	
	
	public static final String	upPressed	= "upPressed";
	public static final String	downPressed	= "downPressed";

	public JIntegerBox(String caption, int value) {
		super(caption, Integer.toString(value));
		upButton = new JButton("+");
		upButton.addActionListener(this);
		
		downButton = new JButton("-");
		downButton.addActionListener(this);
		
		bPanel = new JPanel();
		bPanel.setLayout(new GridLayout(2,1));
		
		bPanel.add(upButton);
		bPanel.add(downButton);
		
		add(bPanel,BorderLayout.EAST);
		
		setOrientation(Orientation.vertical);
		setButtonsVisible(true);
		setEnabled(true);
	}
	
	private int minValue = Integer.MIN_VALUE;
	private int maxValue = Integer.MAX_VALUE;
	
	public boolean checkTextFormat(String S) {
		try {
			Integer	value = Integer.parseInt(S);
			return (value >= getMinValue() && value < getMaxValue());
		} catch (NumberFormatException e) {
			return false;
		}
	}
	
	public int getValue() {
		try {
			return Integer.parseInt(getText());
		} catch (NumberFormatException e) {
			return Integer.parseInt(oldText);
		}
	}
	
	public void setValue(int value) {
		setText(Integer.toString(value));
	}

	public int getMinValue() {
		return minValue;
	}

	public void setMinValue(int minValue) {
		this.minValue = Math.min(minValue, maxValue);
	}

	public int getMaxValue() {
		return maxValue;
	}

	public void setMaxValue(int maxValue) {
		this.maxValue = Math.max(minValue, maxValue);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if (myCmp(e.getSource(), upButton)) {
			setValue(getValue()+1);
		} else if (myCmp(e.getSource(),downButton)) {
			setValue(getValue()-1);
		} else {
			super.actionPerformed(e);
		}
	}

	public boolean isButtonsVisible() {
		return bPanel.isVisible();
	}

	public void setButtonsVisible(boolean buttonsVisible) {
		bPanel.setVisible(buttonsVisible);
	}
	
	@Override
	public void setEnabled(boolean value) {
		super.setEnabled(value);
		bPanel.setEnabled(value);
		upButton.setEnabled(value);
		downButton.setEnabled(value);
		textField.setEnabled(value);
	}
}
